package com.lg.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lg.consumer.client.RpcClient;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.*;

/**
 * 客户端代理类-创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 */
//@ComponentScan
    @Service
public class RpcClientProxy {


        //负载均衡在这个服务层实现吧
    //1定义一个集合用来存储服务器ip
    private static List<RpcClient> rpcclient = new ArrayList<RpcClient>();        //2 获取服务器的两台ip
       static {
           rpcclient.add(new RpcClient("127.0.0.1",8899));
           rpcclient.add(new RpcClient("127.0.0.1",8898));
        }


    //定义一个计数器
    public static int count=0;

       public static RpcClient getRpcClient(){
           //用于实现轮询。 取余， 获取count的值用作数组的下标，传递给RpcClient数组对象
           RpcClient rpcClient1 =  rpcclient.get(count % 2);
           count ++;
           return rpcClient1;
       }




    public static Object createProxy(Class serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1.封装request请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);
                        //2.创建RpcClient对象
                        RpcClient rpcClient = getRpcClient();
                        try {
                            //3.发送消息
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.返回结果
                            Object result = rpcResponse.getResult();
                            //打印
                            System.out.println("当前rpc--ip："+rpcClient.getIp());
                            System.out.println("当前rpc--port："+rpcClient.getPort());
                            System.out.println("当前rpc--msg："+result.toString());
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception e) {
                            throw e;
                        } finally {
                            rpcClient.close();
                        }

                    }
                });
    }
}
